import re
import base64

_PEM_BEGIN_BOUNDARY_PATTERN = re.compile(r'-+BEGIN (\w+)-+')
_PEM_END_BOUNDARY_PATTERN = re.compile(r'-+END (\w+)-+')


_PEM_ITEM = re.compile(rb'-{4}([- ]?)BEGIN ([A-Z ]+)\1-{4}'
                       rb'([A-Za-z0-9+/\-_\r\n]+)'
                       rb'-{4}\1END \2\1-{4}', re.DOTALL)

_PEM_NEWLINE = re.compile(rb'[\r\n]+')

def iter_pem(pem_data: bytes):
    for item in _PEM_ITEM.finditer(pem_data):
        item_type = item.group(2).decode('ascii')
        item_content = base64.standard_b64decode(_PEM_NEWLINE.sub(b'', item.group(3)))
        yield item_type, item_content


def load_pem(pem_data: bytes):
    return [iter_pem(pem_data)]
